<template>
  <el-popover
    placement="top"
    trigger="click"
    :width="width" ref="popoverContainer">
    <template #reference>
      <div class="iconContent" ref="iconContent">
        <template v-if="localValue">
          <component :is="localValue" style="width: 20px;height: 20px;display: inline-block;"></component>
        </template>
        <template v-else>
          <span>请选择图标</span>
        </template>
      </div>
    </template>
    <el-scrollbar>
      <ul class="iconUl">
        <li v-for="(item,value) in ElementPlusIconsVue" :key="item" @click="selectIcon(item,value)">
          <span v-if="false">{{ item }}</span>
          <component :is="value" style="width: 20px;height: 20px;display: inline-block;"></component>
        </li>
      </ul>
    </el-scrollbar>
  </el-popover>
</template>

<script>
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { nextTick, onMounted, ref, toRefs, watch } from 'vue'

export default {
  name: 'iconSelect',
  setup (props, { emit }) {
    const { modelValue } = toRefs(props)
    const localValue = ref(null)
    const width = ref(0)
    const popoverContainer = ref(null)
    const selectIcon = (item, value) => {
      localValue.value = value
      emit('update:modelValue', localValue.value)
      popoverContainer.value.hide()
    }
    const iconContent = ref(null)
    watch(() => modelValue.value, () => {
      localValue.value = modelValue.value
    })
    onMounted(() => {
      nextTick(() => {
        width.value = iconContent.value.clientWidth
        localValue.value = modelValue.value
      })
    })
    return {
      popoverContainer,
      width,
      iconContent,
      selectIcon,
      localValue,
      ElementPlusIconsVue
    }
  },
  props: {
    modelValue: {
      required: true,
      default: ''
    }
  }
}
</script>

<style scoped lang="less">
.iconContent {
  padding: 7px 9px;
  width: 100%;
  border: 1px solid #D4D7DE;
  height: 32px;
  display: flex;
  align-items: center;
  box-sizing: border-box;
  border-radius: 3px;
  cursor: pointer;
  color: #A8ABB2;
}

.iconUl {
  display: flex;
  flex-wrap: wrap;
  height: 150px;
  background: #fff;

  li {
    padding: 5px;
    cursor: pointer;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 30px;
  }

  li:hover {
    background: #2d98e6;
    color: #fff;
  }
}
</style>
